<template>
  <div class="resources-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">
        {{ contentMode === 'hot' ? '热门资源' : 
           contentMode === 'categories' ? '资源分类' : 
           contentMode === 'upload' ? '上传资源' : '学习资源' }}
      </h1>
      <p class="page-subtitle">
        {{ contentMode === 'hot' ? '最受欢迎的学习资料，下载量高，评价好' : 
           contentMode === 'categories' ? '按分类浏览学习资源，快速找到所需内容' : 
           contentMode === 'upload' ? '分享你的学习资料，帮助更多考生备考' : '海量公考学习资料，助力备考成功' }}
      </p>
    </div>

    <!-- 根据不同模式显示不同内容 -->
    <!-- 默认模式：资源中心 -->
    <template v-if="contentMode === 'default'">
      <!-- 搜索和筛选区域 -->
      <div class="search-filter-section">
        <div class="search-form">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索学习资源"
            suffix-icon="Search"
            class="search-input"
          />
          <el-button type="primary" @click="handleSearch" class="search-button">搜索</el-button>
        </div>

        <!-- 高级筛选 -->
        <div class="advanced-filters">
          <el-form :inline="true" :model="filterForm" class="filter-form">
            <el-form-item label="资源类型">
              <el-select v-model="filterForm.resourceType" placeholder="请选择资源类型">
                <el-option label="全部" value="" />
                <el-option label="文档" value="document" />
                <el-option label="视频" value="video" />
                <el-option label="音频" value="audio" />
                <el-option label="图片" value="image" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
            <el-form-item label="文件格式">
              <el-select v-model="filterForm.fileFormat" placeholder="请选择文件格式">
                <el-option label="全部" value="" />
                <el-option label="PDF" value="pdf" />
                <el-option label="Word" value="doc" />
                <el-option label="Excel" value="xls" />
                <el-option label="PPT" value="ppt" />
                <el-option label="视频" value="video" />
              </el-select>
            </el-form-item>
            <el-form-item label="分类">
              <el-select v-model="filterForm.category" placeholder="请选择分类">
                <el-option label="全部" value="" />
                <el-option label="行测资料" value="1" />
                <el-option label="申论资料" value="2" />
                <el-option label="面试资料" value="3" />
                <el-option label="真题解析" value="4" />
                <el-option label="备考经验" value="5" />
                <el-option label="政策法规" value="6" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="resetFilter">重置筛选</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 资源列表 -->
      <div class="resources-section">
        <div class="resources-header">
          <div class="resources-info">
            <span class="resources-count">共找到 {{ filteredResources.length }} 个学习资源</span>
          </div>
          <div class="sort-options">
            <el-select v-model="sortBy" placeholder="排序方式">
              <el-option label="默认排序" value="default" />
              <el-option label="下载量从高到低" value="downloads_desc" />
              <el-option label="下载量从低到高" value="downloads_asc" />
              <el-option label="浏览量从高到低" value="views_desc" />
              <el-option label="浏览量从低到高" value="views_asc" />
              <el-option label="收藏量从高到低" value="favorites_desc" />
              <el-option label="收藏量从低到高" value="favorites_asc" />
              <el-option label="发布时间从新到旧" value="created_desc" />
              <el-option label="发布时间从旧到新" value="created_asc" />
            </el-select>
          </div>
        </div>

        <div class="resources-grid">
          <ResourceCard 
            v-for="resource in filteredResources" 
            :key="resource.id"
            :resource="resource"
            :show-author="true"
            :show-actions="true"
            class="resource-card-item"
          />
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalResources"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </template>

    <!-- 热门资源模式 -->
    <template v-else-if="contentMode === 'hot'">
      <div class="resources-section">
        <div class="resources-header">
          <div class="resources-info">
            <span class="resources-count">共找到 {{ filteredResources.length }} 个热门资源</span>
          </div>
        </div>

        <div class="resources-grid">
          <ResourceCard 
            v-for="resource in filteredResources" 
            :key="resource.id"
            :resource="resource"
            :show-author="true"
            :show-actions="true"
            class="resource-card-item"
          />
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalResources"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </template>

    <!-- 资源分类模式 -->
    <template v-else-if="contentMode === 'categories'">
      <div class="categories-section">
        <div class="categories-grid">
          <div 
            v-for="category in resourceCategories" 
            :key="category.id"
            class="category-card"
          >
            <div class="category-icon">
              <el-icon><{{ category.icon }} /></el-icon>
            </div>
            <div class="category-info">
              <h3 class="category-name">{{ category.name }}</h3>
              <p class="category-count">{{ category.count }} 个资源</p>
            </div>
          </div>
        </div>
      </div>
    </template>

    <!-- 上传资源模式 -->
    <template v-else-if="contentMode === 'upload'">
      <div class="upload-section">
        <el-form :model="uploadForm" label-width="120px" class="upload-form">
          <el-form-item label="资源标题" prop="title">
            <el-input v-model="uploadForm.title" placeholder="请输入资源标题" />
          </el-form-item>
          <el-form-item label="资源描述" prop="description">
            <el-input type="textarea" v-model="uploadForm.description" placeholder="请输入资源描述" :rows="4" />
          </el-form-item>
          <el-form-item label="资源类型">
            <el-select v-model="uploadForm.resourceType" placeholder="请选择资源类型">
              <el-option label="文档" value="document" />
              <el-option label="视频" value="video" />
              <el-option label="音频" value="audio" />
              <el-option label="图片" value="image" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
          <el-form-item label="文件格式">
            <el-select v-model="uploadForm.fileFormat" placeholder="请选择文件格式">
              <el-option label="PDF" value="pdf" />
              <el-option label="Word" value="doc" />
              <el-option label="Excel" value="xls" />
              <el-option label="PPT" value="ppt" />
              <el-option label="视频" value="video" />
            </el-select>
          </el-form-item>
          <el-form-item label="资源分类">
            <el-select v-model="uploadForm.category" placeholder="请选择资源分类">
              <el-option label="行测资料" value="1" />
              <el-option label="申论资料" value="2" />
              <el-option label="面试资料" value="3" />
              <el-option label="真题解析" value="4" />
              <el-option label="备考经验" value="5" />
              <el-option label="政策法规" value="6" />
            </el-select>
          </el-form-item>
          <el-form-item label="上传文件">
            <el-upload
               class="upload-demo"
               action=""
               :http-request="() => {}"
               :before-upload="() => false"
               :show-file-list="false"
             >
               <el-button type="primary" @click="handleFileSelect">选择文件</el-button>
               <input 
                 id="file-upload"
                 ref="fileInput"
                 type="file" 
                 style="display: none" 
                 @change="handleFileChange"
               />
               <span v-if="uploadForm.file" style="margin-left: 10px;">{{ uploadForm.file.name }}</span>
             </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleUpload">提交上传</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import ResourceCard from '@/components/ResourceCard.vue';
import { searchResources, getResourceCategories } from '@/api/resource';

// 获取当前路由
const route = useRoute();

// 搜索关键词
const searchKeyword = ref('');

// 数据状态
const loading = ref(false);
const mockResources = ref<any[]>([]);
const resourceCategories = ref<any[]>([]);

// 筛选表单
const filterForm = ref({
  resourceType: '',
  fileFormat: '',
  category: ''
});

// 排序方式
const sortBy = ref('default');

// 分页数据
const currentPage = ref(1);
const pageSize = ref(10);
const totalResources = ref(200);

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    // 并行加载资源和分类数据
    const [resourcesData, categoriesData] = await Promise.all([
      searchResources({ page: 1, pageSize: 20 }),
      getResourceCategories()
    ]);
    
    mockResources.value = resourcesData?.items || [];
    resourceCategories.value = categoriesData || [];
  } catch (error) {
    console.error('加载数据失败:', error);
    // 如果API调用失败，使用模拟数据作为后备
    loadMockData();
  } finally {
    loading.value = false;
  }
};

// 加载模拟数据作为后备（当API失败时使用）
const loadMockData = () => {
  mockResources.value = [
    {
      id: 1,
      title: '2024年公务员考试行测必做1000题',
      description: '精选历年行测真题和高质量模拟题，包含详细解析和解题技巧',
      type: 'pdf',
      category: { id: 1, name: '行测资料' },
      tags: [{ id: 1, name: '行测' }, { id: 2, name: '真题' }, { id: 3, name: '必做' }],
      coverImage: 'https://picsum.photos/id/24/300/200',
      downloadCount: 1254,
      viewCount: 3689,
      favoriteCount: 567,
      commentCount: 123,
      author: {
        id: 3,
        username: '资料大全',
        avatar: 'https://picsum.photos/id/1025/200/200'
      },
      createdAt: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()
    },
    {
      id: 2,
      title: '申论范文100篇：高分作文精选',
      description: '收集整理各类申论主题的高分范文，帮助考生提升写作水平',
      type: 'pdf',
      category: { id: 2, name: '申论资料' },
      tags: [{ id: 4, name: '申论' }, { id: 5, name: '范文' }, { id: 6, name: '高分' }],
      coverImage: 'https://picsum.photos/id/25/300/200',
      downloadCount: 2103,
      viewCount: 5782,
      favoriteCount: 894,
      commentCount: 234,
      author: {
        id: 4,
        username: '写作大师',
        avatar: 'https://picsum.photos/id/1027/200/200'
      },
      createdAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString()
    },
    {
      id: 3,
      title: '2023年国考面试真题及解析',
      description: '2023年国家公务员考试面试真题汇总，包含详细解析和参考答案',
      type: 'document',
      category: { id: 3, name: '面试资料' },
      tags: [{ id: 7, name: '面试' }, { id: 8, name: '真题' }, { id: 9, name: '2023' }],
      coverImage: 'https://picsum.photos/id/26/300/200',
      downloadCount: 1567,
      viewCount: 4231,
      favoriteCount: 678,
      commentCount: 189,
      author: {
        id: 5,
        username: '面试专家',
        avatar: 'https://picsum.photos/id/1035/200/200'
      },
      createdAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString()
    },
    {
      id: 4,
      title: '行测图形推理专项突破视频课程',
      description: '15小时图形推理专项讲解，从基础到进阶，帮你攻克图形推理难关',
      type: 'video',
      category: { id: 1, name: '行测资料' },
      tags: [{ id: 10, name: '行测' }, { id: 11, name: '图形推理' }, { id: 12, name: '视频' }],
      coverImage: 'https://picsum.photos/id/27/300/200',
      downloadCount: 890,
      viewCount: 2345,
      favoriteCount: 456,
      commentCount: 123,
      author: {
        id: 6,
        username: '行测名师',
        avatar: 'https://picsum.photos/id/1040/200/200'
      },
      createdAt: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString()
    }
  ];

  resourceCategories.value = [
    { id: 1, name: '行测资料', icon: 'Document', count: 568 },
    { id: 2, name: '申论资料', icon: 'DocumentText', count: 432 },
    { id: 3, name: '面试资料', icon: 'MessageSquare', count: 298 },
    { id: 4, name: '真题解析', icon: 'FileText', count: 789 },
    { id: 5, name: '备考经验', icon: 'BookOpen', count: 345 },
    { id: 6, name: '政策法规', icon: 'FileCheck', count: 123 }
  ];
};

// 组件挂载时加载数据
onMounted(() => {
  loadData();
});

// 计算当前内容模式（根据路由路径）
const contentMode = computed(() => {
  const path = route.path;
  if (path.includes('/resources/hot')) return 'hot';
  if (path.includes('/resources/categories')) return 'categories';
  if (path.includes('/resources/upload')) return 'upload';
  return 'default'; // 默认是资源中心
});

// 上传表单数据
interface UploadFormType {
  title: string;
  description: string;
  resourceType: string;
  fileFormat: string;
  category: string;
  file: File | null;
}

const uploadForm = ref<UploadFormType>({
  title: '',
  description: '',
  resourceType: '',
  fileFormat: '',
  category: '',
  file: null
});

// 根据搜索和筛选条件处理资源列表
const filteredResources = computed(() => {
  let resources = [...mockResources.value];
  
  // 根据关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    resources = resources.filter(resource => 
      resource.title.toLowerCase().includes(keyword) ||
      resource.description.toLowerCase().includes(keyword) ||
      (resource.category && resource.category.name.toLowerCase().includes(keyword)) ||
      (resource.tags && resource.tags.some((tag: any) =>
        tag.name && tag.name.toLowerCase().includes(keyword)
      ))
    );
  }
  
  // 根据资源类型筛选
  if (filterForm.value.resourceType) {
    resources = resources.filter(resource => resource.type === filterForm.value.resourceType);
  }
  
  // 根据文件格式筛选
  if (filterForm.value.fileFormat) {
    resources = resources.filter(resource => {
      if (filterForm.value.fileFormat === 'pdf' && resource.type === 'pdf') return true;
      if (filterForm.value.fileFormat === 'doc' && resource.type === 'document') return true;
      if (filterForm.value.fileFormat === 'video' && resource.type === 'video') return true;
      return false;
    });
  }
  
  // 根据分类筛选
  if (filterForm.value.category) {
    resources = resources.filter(resource => 
      resource.category && resource.category.id.toString() === filterForm.value.category
    );
  }
  
  // 根据排序方式排序
  switch (sortBy.value) {
    case 'downloads_desc':
      resources.sort((a, b) => (b.downloadCount || 0) - (a.downloadCount || 0));
      break;
    case 'downloads_asc':
      resources.sort((a, b) => (a.downloadCount || 0) - (b.downloadCount || 0));
      break;
    case 'views_desc':
      resources.sort((a, b) => (b.viewCount || 0) - (a.viewCount || 0));
      break;
    case 'views_asc':
      resources.sort((a, b) => (a.viewCount || 0) - (b.viewCount || 0));
      break;
    case 'favorites_desc':
      resources.sort((a, b) => (b.favoriteCount || 0) - (a.favoriteCount || 0));
      break;
    case 'favorites_asc':
      resources.sort((a, b) => (a.favoriteCount || 0) - (b.favoriteCount || 0));
      break;
    case 'created_desc':
      resources.sort((a, b) => (new Date(b.createdAt || '').getTime() || 0) - (new Date(a.createdAt || '').getTime() || 0));
      break;
    case 'created_asc':
      resources.sort((a, b) => (new Date(a.createdAt || '').getTime() || 0) - (new Date(b.createdAt || '').getTime() || 0));
      break;
    default:
      break;
  }
  
  // 如果是热门资源页面，直接按下载量排序
  if (contentMode.value === 'hot') {
    resources.sort((a, b) => (b.downloadCount || 0) - (a.downloadCount || 0));
  }
  
  return resources;
});

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1; // 搜索时重置为第一页
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.value = {
    resourceType: '',
    fileFormat: '',
    category: ''
  };
  searchKeyword.value = '';
  currentPage.value = 1;
};

// 分页大小变化处理
const handleSizeChange = (size: number) => {
  pageSize.value = size;
};

// 页码变化处理
const handleCurrentChange = (current: number) => {
  currentPage.value = current;
};

// 上传资源处理
const handleUpload = () => {
  // 这里应该有上传资源的逻辑
  // 模拟上传成功
  alert('资源上传成功！');
  uploadForm.value = {
    title: '',
    description: '',
    resourceType: '',
    fileFormat: '',
    category: '',
    file: null
  };
};

// 文件选择处理
const handleFileChange = (e: Event) => {
  const target = e.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    uploadForm.value.file = target.files[0] as File;
  }
};

// 触发文件选择对话框
const handleFileSelect = () => {
  const fileInput = document.getElementById('file-upload') as HTMLInputElement;
  if (fileInput) {
    fileInput.click();
  }
};
</script>

<style lang="scss" scoped>
.resources-view {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 40px 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);

  .page-title {
    font-size: 2.5rem;
    font-weight: 700;
    margin-bottom: 10px;
  }

  .page-subtitle {
    font-size: 1.2rem;
    opacity: 0.9;
  }
}

.search-filter-section {
  margin-bottom: 30px;

  .search-form {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;

    .search-input {
      flex: 1;
      max-width: 800px;
    }

    .search-button {
      min-width: 100px;
    }
  }

  .advanced-filters {
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .filter-form {
      .el-form-item {
        margin-right: 20px;
        margin-bottom: 0;

        .el-select {
          min-width: 120px;
        }
      }
    }
  }
}

.resources-section {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .resources-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e2e8f0;

    .resources-info {
      .resources-count {
        font-size: 16px;
        color: #666;
      }
    }

    .sort-options {
      .el-select {
        min-width: 150px;
      }
    }
  }

  .resources-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #e2e8f0;

    .el-pagination {
      .el-pager li {
        margin: 0 4px;
        min-width: 32px;
        height: 32px;
        line-height: 32px;
        font-size: 14px;
      }
    }
  }
}

/* 分类页面样式 */
.categories-section {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.category-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      border-color: #667eea;
    }
}

.category-icon {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 50%;
  margin-right: 20px;
  font-size: 24px;
}

.category-info {
  flex: 1;
}

.category-name {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 5px;
  color: #333;
}

.category-count {
  font-size: 14px;
  color: #666;
}

/* 上传页面样式 */
.upload-section {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.upload-form {
  max-width: 800px;
  margin: 0 auto;
}

.upload-form .el-form-item {
  margin-bottom: 25px;
}

.upload-form .el-textarea {
  width: 100%;
}
</style>